<?php

namespace app\model;

use think\Model;
use think\model\relation\HasMany;

class Package extends Model
{
    public function savePack(): array
    {
        $data = request()->post();
        $attr = $data['productAttr'];
        unset($data['productAttr']);
        if (empty($attr)) throw new \Exception('礼包中至少包含一个规格礼包属性', 7002);
        $data['content'] = htmlentities($data['content']);
        $attrModel = app(PackageAttr::class);
        $defaultAttr = [];
        if (!empty($data['id'])) {
            $defaultAttr = $attrModel->where(['pack' => $data['id']])->select()->toArray();
            $defaultAttr = array_column($defaultAttr, "id");
        }
        $this->startTrans();
        $this->exists(!empty($data['id']))->save($data);
        $insertAttr = $updateAttr = [];
        foreach ($attr as $value) {
            $value = array_filter($value);
            if (empty($value)) throw new \Exception('礼包规格属性不能为空', 7003);
            $value['pack'] = $this->id;
            $value['image'] = $this->image ?? "";
            $value['create_time'] = $value['update_time'] = date('Y-m-d H:i:s');
            if (!empty($value['id'])) {
                unset($value['create_time']);
                $updateAttr[] = $value;
            } else {
                $insertAttr[] = $value;
            }
        }
        if (!empty($insertAttr)) $attrModel->insertAll($insertAttr);
        if (!empty($updateAttr)) {
            $attrModel->exists()->saveAll($updateAttr);
            $id = array_diff($defaultAttr, array_column($updateAttr, 'id'));
            if (!empty($id)) {
                //删除已无用规格
                $attrModel->whereIn('id', $id)->delete();
            }
        }
        $this->commit();
        return $this->toArray();
    }

    public function productAttr(): HasMany
    {
        return $this->hasMany(PackageAttr::class, 'pack', 'id');
    }

    public function pageData(): array
    {
        $data = request()->param();
        $pages = $this->withCount(['productAttr'])->when(!empty($data['name']), function ($query) use ($data) {
            $query->whereLike('name', "%{$data['name']}%");
        })->where(['is_del' => 1])->order(['create_time' => 'desc'])->paginate([
            "list_rows" => $data['pageSize'] ?? 30,
            "page" => $data['page'] ?? 1
        ])->toArray();
        return ['lst' => $pages['data'], 'total' => $pages['total']];
    }

    public function product(): HasMany
    {
        return $this->hasMany(PackageProduct::class, 'pack', 'id');
    }

    public function detail()
    {
        $id = request()->param('id');
        $data = $this->with(['productAttr' => function ($query) {
            $query->with(['product' => function ($q) {
                $q->with(['productData']);
            }])->field("id,pack,name,prices,sku,change_number");
        }, 'product' => function ($query) {
            $query->hidden(['create_time', 'update_time'])->order('attr,product');
        }])->findOrFail($id)->toArray();
        $data['content'] = htmlspecialchars_decode($data['content']);
        return $data;
    }

    public function deleteData()
    {
        $id = request()->param("id");
        $its = $this->findOrFail($id);
        $its->is_del = 0;
        return $its->save();
    }

    public function lst()
    {
        return $this->where(['is_del' => 1, 'state' => 1])->select()->toArray();
    }
}
